<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="admin.Connectmysql" %>
<%
    // 检查登录
    HttpSession userSession = request.getSession(false);
    if (userSession == null || userSession.getAttribute("student_id") == null) {
        response.sendRedirect("student_login.jsp");
        return;
    }

    int studentId = (int) userSession.getAttribute("student_id");
    String studentName = (String) userSession.getAttribute("student_name");

    // 获取考试ID
    String examIdParam = request.getParameter("exam_id");
    if(examIdParam == null || examIdParam.trim().isEmpty()) {
        examIdParam = (String) userSession.getAttribute("currentExamId");
    }

    if(examIdParam == null || examIdParam.trim().isEmpty()) {
        response.sendRedirect("student.jsp#exams");
        return;
    }

    int examId;
    try {
        examId = Integer.parseInt(examIdParam);
    } catch(NumberFormatException e) {
        response.sendRedirect("student.jsp#exams");
        return;
    }

    // 存储考试ID到session
    userSession.setAttribute("currentExamId", examIdParam);

    // 考试信息
    String examName = "";
    String courseName = "";
    Timestamp startTime = null;
    int duration = 60;
    double totalScore = 100;

    // 考试题目
    List<Map<String, Object>> questions = new ArrayList<>();

    Connectmysql conn = new Connectmysql(
            "jdbc:mysql://localhost:3306/exam",
            "root", "root", "com.mysql.cj.jdbc.Driver"
    );

    try {
        if(!conn.open()) throw new Exception("数据库连接失败");

        // 验证学生权限
        String verifySql = "SELECT ec.class_id " +
                "FROM exam_class ec " +
                "JOIN student s ON ec.class_id = s.class_id " +
                "WHERE ec.exam_id = ? AND s.student_id = ?";
        ResultSet verifyRs = conn.executeSql(verifySql, new Object[]{examId, studentId});
        if (!verifyRs.next()) {
            response.sendRedirect("student.jsp#exams");
            return;
        }

        // 获取考试信息
        String examSql = "SELECT e.exam_name, c.course_name, e.start_time, " +
                "e.duration, e.status, e.total_score " +
                "FROM exam e " +
                "JOIN course c ON e.course_id = c.course_id " +
                "WHERE e.exam_id = ?";
        ResultSet examRs = conn.executeSql(examSql, new Object[]{examId});

        if (examRs.next()) {
            examName = examRs.getString("exam_name");
            courseName = examRs.getString("course_name");
            startTime = examRs.getTimestamp("start_time");
            duration = examRs.getInt("duration");
            totalScore = examRs.getDouble("total_score");

            // 检查考试状态
            int status = examRs.getInt("status");
            if(status != 2) {
                response.sendRedirect("student.jsp#exams");
                return;
            }
        } else {
            response.sendRedirect("student.jsp#exams");
            return;
        }

        // 获取考试题目
        String questionsSql = "SELECT q.question_id, q.question_text, q.option_a, q.option_b, " +
                "q.option_c, q.option_d, q.correct_answer, q.score, eq.sort_order " +
                "FROM exam_question eq " +
                "JOIN question q ON eq.question_id = q.question_id " +
                "WHERE eq.exam_id = ? " +
                "ORDER BY eq.sort_order ASC";
        ResultSet qRs = conn.executeSql(questionsSql, new Object[]{examId});

        while(qRs.next()) {
            Map<String, Object> q = new HashMap<>();
            q.put("question_id", qRs.getInt("question_id"));
            q.put("question_text", qRs.getString("question_text"));
            q.put("option_a", qRs.getString("option_a"));
            q.put("option_b", qRs.getString("option_b"));
            q.put("option_c", qRs.getString("option_c"));
            q.put("option_d", qRs.getString("option_d"));
            q.put("correct_answer", qRs.getString("correct_answer"));
            q.put("score", qRs.getDouble("score"));
            q.put("sort_order", qRs.getInt("sort_order"));
            questions.add(q);
        }

        if(questions.isEmpty()) {
            response.sendRedirect("student.jsp#exams");
            return;
        }
    } catch(Exception e) {
        e.printStackTrace();
        response.sendRedirect("student.jsp#exams");
        return;
    }
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线考试系统 - <%= examName %></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* 保持原有的样式不变 */
        .exam-container {
            max-width: 800px;
            margin: 2rem auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            font-family: 'Inter', sans-serif;
        }
        .exam-header {
            background: linear-gradient(135deg, #165DFF 0%, #0FC6C2 100%);
            color: white;
            padding: 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .timer {
            font-size: 1.5rem;
            font-weight: bold;
            background: rgba(255, 255, 255, 0.2);
            padding: 0.5rem 1.2rem;
            border-radius: 30px;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }
        .question-container {
            padding: 1.5rem;
            border-bottom: 1px solid #e5e7eb;
            background: #f9fafb;
            min-height: 400px;
        }
        .question-text {
            font-size: 1.15rem;
            font-weight: 500;
            margin-bottom: 1.5rem;
            line-height: 1.6;
            color: #1f2937;
        }
        .options-container {
            display: grid;
            gap: 0.8rem;
        }
        .option {
            display: flex;
            align-items: flex-start;
            padding: 1rem;
            background: white;
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        .option:hover {
            border-color: #93c5fd;
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }
        .option.selected {
            border-color: #165DFF;
            background-color: #ebf5ff;
        }
        .option input {
            margin-top: 3px;
            margin-right: 12px;
            flex-shrink: 0;
        }
        .option-label {
            font-size: 1rem;
            color: #374151;
            line-height: 1.5;
        }
        .navigation {
            display: flex;
            justify-content: space-between;
            padding: 1.5rem;
            background-color: #f9fafb;
            align-items: center;
        }
        .question-counter {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            max-width: 300px;
        }
        .question-dot {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #e5e7eb;
            cursor: pointer;
            font-size: 0.95rem;
            font-weight: 500;
            transition: all 0.2s;
        }
        .question-dot.answered {
            background: #165DFF;
            color: white;
        }
        .question-dot.current {
            border: 3px solid #165DFF;
            background: white;
            color: #165DFF;
            font-weight: bold;
        }
        .btn-submit {
            background: linear-gradient(135deg, #00B42A 0%, #009a23 100%);
            color: white;
            font-weight: 600;
            padding: 0.8rem 1.8rem;
            border-radius: 10px;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            font-size: 1rem;
        }
        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 180, 42, 0.3);
        }
        .btn-submit:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .btn-nav {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.7rem 1.2rem;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.2s;
        }
        .btn-prev {
            background: #f3f4f6;
            color: #4b5563;
            border: 1px solid #e5e7eb;
        }
        .btn-prev:hover {
            background: #e5e7eb;
        }
        .btn-next {
            background: #165DFF;
            color: white;
            border: 1px solid #165DFF;
        }
        .btn-next:hover {
            background: #0e4bc0;
        }
        .btn-finish {
            background: #f97316;
            color: white;
            border: 1px solid #f97316;
            margin-left: 0.5rem;
        }
        .btn-finish:hover {
            background: #ea580c;
        }
        .btn-retry {
            background: #165DFF;
            color: white;
            border: 1px solid #165DFF;
            padding: 0.8rem 1.8rem;
            border-radius: 8px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        .btn-retry:hover {
            background: #0e4bc0;
            transform: translateY(-2px);
        }
        .progress-container {
            width: 100%;
            height: 8px;
            background: #e5e7eb;
            border-radius: 4px;
            margin-top: 1rem;
            overflow: hidden;
        }
        .progress-bar {
            height: 100%;
            background: #165DFF;
            border-radius: 4px;
            transition: width 0.3s ease;
        }
        .time-warning {
            animation: pulse 1.5s infinite;
        }
        @keyframes pulse {
            0% { background-color: rgba(245, 63, 63, 0.2); }
            50% { background-color: rgba(245, 63, 63, 0.4); }
            100% { background-color: rgba(245, 63, 63, 0.2); }
        }
        .loading-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 1rem;
            padding: 2rem;
        }
        .loading-spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 4px solid #165DFF;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .error-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 1.5rem;
            text-align: center;
            padding: 1.5rem;
        }
        .error-icon {
            font-size: 3rem;
            color: #f53f3f;
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: rgba(245, 63, 63, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .debug-container {
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
            width: 100%;
            max-width: 90%;
        }
        .debug-item {
            display: flex;
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
        }
        .debug-label {
            width: 160px;
            font-weight: 500;
            color: #4b5563;
        }
        .debug-value {
            color: #1f2937;
        }
        .result-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        .result-modal.active {
            opacity: 1;
            visibility: visible;
        }
        .result-content {
            background: white;
            border-radius: 12px;
            max-width: 500px;
            width: 100%;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            transform: translateY(-20px);
            opacity: 0;
            transition: all 0.3s ease 0.1s;
        }
        .result-modal.active .result-content {
            transform: translateY(0);
            opacity: 1;
        }
        .result-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .result-body {
            padding: 2rem;
        }
        .result-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1.5rem;
            font-size: 2.5rem;
        }
        .result-icon.success {
            background: rgba(0, 180, 42, 0.1);
            color: #00B42A;
        }
        .result-stats {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
            margin: 1.5rem 0;
        }
        .stat-box {
            background: #f9fafb;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
        }
        .header-info {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }
        .student-info {
            display: flex;
            gap: 15px;
            font-size: 0.9rem;
            margin-top: 5px;
        }
        .info-item {
            display: flex;
            align-items: center;
            gap: 4px;
            background: rgba(255, 255, 255, 0.15);
            padding: 2px 8px;
            border-radius: 12px;
        }
        .param-debug {
            position: fixed;
            top: 10px;
            right: 10px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 10px;
            border-radius: 5px;
            z-index: 1000;
            font-size: 12px;
            max-width: 300px;
        }
    </style>
</head>
<body class="bg-gray-100">
<div class="exam-container">
    <div class="exam-header">
        <div class="header-info">
            <h1 class="text-xl font-bold"><%= examName %></h1>
            <p class="text-blue-100"><%= courseName %></p>
            <div class="student-info">
                <div class="info-item">
                    <i class="fa fa-user"></i>
                    <span><%= studentName %></span>
                </div>
                <div class="info-item">
                    <i class="fa fa-id-card"></i>
                    <span><%= studentId %></span>
                </div>
            </div>
        </div>
        <div class="timer" id="timer">
            <i class="fa fa-clock-o"></i>
            <span id="time-display">60:00</span>
        </div>
    </div>

    <!-- 考试表单 -->
    <form id="exam-form" action="submitExam.jsp" method="post">
        <input type="hidden" name="exam_id" value="<%= examId %>">
        <input type="hidden" name="student_id" value="<%= studentId %>">

        <div class="question-container">
            <div id="exam-content">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-700">题目 <span id="current-question">1</span> / <span id="total-questions"><%= questions.size() %></span></h3>
                    <div class="text-sm font-medium text-gray-500">
                        分值: <span id="question-score">0</span> 分
                    </div>
                </div>

                <div class="progress-container">
                    <div class="progress-bar" id="progress-bar" style="width: 0%"></div>
                </div>

                <div class="options-container mt-6">
                    <%
                        for(int i = 0; i < questions.size(); i++) {
                            Map<String, Object> q = questions.get(i);
                            int qid = (int) q.get("question_id");
                            double score = (double) q.get("score");
                    %>
                    <div class="question-view" style="<%= i == 0 ? "display: block;" : "display: none;" %>" id="question-<%= qid %>" data-index="<%= i %>">
                        <div class="question-text"><%= q.get("question_text") %></div>
                        <div class="options-container mt-4">
                            <div class="option">
                                <input type="radio" name="answer_<%= qid %>" id="option_<%= qid %>_A" value="A">
                                <label for="option_<%= qid %>_A" class="option-label">A. <%= q.get("option_a") %></label>
                            </div>
                            <div class="option">
                                <input type="radio" name="answer_<%= qid %>" id="option_<%= qid %>_B" value="B">
                                <label for="option_<%= qid %>_B" class="option-label">B. <%= q.get("option_b") %></label>
                            </div>
                            <div class="option">
                                <input type="radio" name="answer_<%= qid %>" id="option_<%= qid %>_C" value="C">
                                <label for="option_<%= qid %>_C" class="option-label">C. <%= q.get("option_c") %></label>
                            </div>
                            <div class="option">
                                <input type="radio" name="answer_<%= qid %>" id="option_<%= qid %>_D" value="D">
                                <label for="option_<%= qid %>_D" class="option-label">D. <%= q.get("option_d") %></label>
                            </div>
                        </div>
                        <input type="hidden" name="question_id_<%= qid %>" value="<%= qid %>">
                        <input type="hidden" name="score_<%= qid %>" value="<%= score %>">
                        <input type="hidden" name="correct_answer_<%= qid %>" value="<%= q.get("correct_answer") %>">
                    </div>
                    <% } %>
                </div>
            </div>
        </div>

        <div class="navigation">
            <div class="flex">
                <button type="button" id="btn-prev" class="btn-nav btn-prev">
                    <i class="fa fa-arrow-left"></i>上一题
                </button>
                <button type="button" id="btn-next" class="btn-nav btn-next ml-2">
                    下一题<i class="fa fa-arrow-right ml-1"></i>
                </button>
                <button type="button" id="btn-finish" class="btn-nav btn-finish">
                    <i class="fa fa-flag"></i>结束答题
                </button>
            </div>

            <div class="question-counter">
                <% for(int i = 0; i < questions.size(); i++) { %>
                <div class="question-dot <%= i == 0 ? "current" : "" %>" data-index="<%= i %>">
                    <%= i+1 %>
                </div>
                <% } %>
            </div>
        </div>
    </form>
</div>

<script>
    // 全局变量
    const totalQuestions = <%= questions.size() %>;
    let currentQuestionIndex = 0;
    let timerInterval;
    let examDuration = <%= duration %>;
    let timeLeft = examDuration * 60;

    // 页面初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 开始计时器
        startTimer();

        // 初始化问题计数器
        updateQuestionCounter();

        // 按钮事件
        document.getElementById('btn-prev').addEventListener('click', showPreviousQuestion);
        document.getElementById('btn-next').addEventListener('click', showNextQuestion);
        document.getElementById('btn-finish').addEventListener('click', finishExam);
        document.querySelectorAll('.question-dot').forEach(dot => {
            dot.addEventListener('click', function() {
                const index = parseInt(this.getAttribute('data-index'));
                showQuestion(index);
            });
        });
    });

    // 显示指定问题
    function showQuestion(index) {
        if (index < 0 || index >= totalQuestions) return;

        // 隐藏所有问题
        document.querySelectorAll('.question-view').forEach(view => {
            view.style.display = 'none';
        });

        // 显示新问题
        currentQuestionIndex = index;
        const questionViews = document.querySelectorAll('.question-view');
        const questionView = questionViews[index];
        questionView.style.display = 'block';

        // 更新UI
        document.getElementById('current-question').textContent = index + 1;
        const questionId = questionView.id.split('-')[1];
        const score = document.querySelector(`input[name="score_${questionId}"]`).value;
        document.getElementById('question-score').textContent = parseFloat(score).toFixed(1);

        // 更新进度条
        const progress = ((index + 1) / totalQuestions) * 100;
        document.getElementById('progress-bar').style.width = `${progress}%`;

        // 更新导航按钮状态
        document.getElementById('btn-prev').disabled = (index === 0);
        document.getElementById('btn-next').disabled = (index === totalQuestions - 1);

        // 更新问题计数器
        updateQuestionCounter();
    }

    // 显示上一题
    function showPreviousQuestion() {
        showQuestion(currentQuestionIndex - 1);
    }

    // 显示下一题
    function showNextQuestion() {
        showQuestion(currentQuestionIndex + 1);
    }

    // 更新题目计数器
    function updateQuestionCounter() {
        const dots = document.querySelectorAll('.question-dot');
        dots.forEach((dot, index) => {
            dot.classList.remove('current', 'answered');
            if(index === currentQuestionIndex) {
                dot.classList.add('current');
            }

            // 检查该问题是否已回答
            const questionViews = document.querySelectorAll('.question-view');
            const questionView = questionViews[index];
            const questionId = questionView.id.split('-')[1];
            const selectedAnswer = document.querySelector(`input[name="answer_${questionId}"]:checked`);

            if(selectedAnswer) {
                dot.classList.add('answered');
            }
        });
    }

    // 开始计时器
    function startTimer() {
        updateTimerDisplay(timeLeft);

        timerInterval = setInterval(() => {
            timeLeft--;
            updateTimerDisplay(timeLeft);

            if (timeLeft <= 0) {
                clearInterval(timerInterval);
                alert('考试时间已结束！');
                submitExamForm();
            }

            // 最后5分钟添加警告效果
            if (timeLeft <= 5 * 60) {
                document.getElementById('timer').classList.add('time-warning');
            }
        }, 1000);
    }

    // 更新计时器显示
    function updateTimerDisplay(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        document.getElementById('time-display').textContent =
            `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;

        // 最后5分钟变为红色
        if (minutes < 5) {
            document.getElementById('timer').style.color = '#F53F3F';
            document.getElementById('timer').style.backgroundColor = 'rgba(245, 63, 63, 0.2)';
        }
    }

    // 结束考试
    function finishExam() {
        if (!confirm('确定要结束答题并提交试卷吗？提交后将无法修改！')) {
            return;
        }
        submitExamForm();
    }

    // 提交表单
    function submitExamForm() {
        clearInterval(timerInterval);
        document.getElementById('exam-form').submit();
    }
</script>
</body>
</html>